package easier.fast.web;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import easier.fast.R;
import easier.fast.page.pull.BaseRefreshTitleActivity;
import easier.fast.page.pull.TitleCode;
import easier.fast.service.ApiService;
import easier.recycler.MultiTypeAdapter.BaseViewHolder;
import easier.recycler.MultiTypeAdapter.TypeViewHolder;
import io.reactivex.rxjava3.core.Observable;
import java.util.ArrayList;
import java.util.List;

public class WebActivity extends BaseRefreshTitleActivity< String > {

    public static final String extra_title = "extra_title";
    public static final String extra_url = "extra_url";

    private String mTitle = "";
    private String mUrl = "";

    public static void start( Context context, String title, String url ) {

        Intent starter = new Intent( context, WebActivity.class );
        starter.putExtra( extra_title, title );
        starter.putExtra( extra_url, url );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( @Nullable Bundle savedInstanceState ) {

        if ( getIntent() == null ) {
            if ( savedInstanceState != null ) {
                mTitle = savedInstanceState.getString( extra_title );
                mUrl = savedInstanceState.getString( extra_url );
            }
        } else {
            mTitle = getIntent().getStringExtra( extra_title );
            mUrl = getIntent().getStringExtra( extra_url );
        }

        super.onCreate( savedInstanceState );
    }

    @Override
    protected void onSaveInstanceState( @NonNull Bundle outState ) {

        outState.putString( extra_title, mTitle );
        outState.putString( extra_url, mUrl );

        super.onSaveInstanceState( outState );
    }

    @Override
    protected void initViewAction() {

        super.initViewAction();

        TitleCode.initTitleAction( this, mTitle );
    }

    @Override
    protected Observable< String > createRequest( Context context ) {

        return ApiService.get( context, mUrl );
    }

    @Override
    protected List< TypeViewHolder > createContentView( Context context, String s ) {

        List< TypeViewHolder > list = new ArrayList<>();
        list.add( build( s ) );
        return list;
    }

    private TypeViewHolder build( String s ) {

        return new BaseViewHolder( R.layout.activity_web ) {

            @Override
            protected void onBind( ViewHolder viewHolder, View root, int position, int type ) {

                super.onBind( viewHolder, root, position, type );

                View view = root.findViewById( R.id.webView );
                ((WebView) view).loadData( s, "text/html", "utf-8" );
            }
        };
    }
}